import logging
import uuid
from flask import g, has_app_context

"""
为logging record 添加 trace_id

Copyright (C) chengpeng.hu. All Rights Reserved

@Author  : chengpeng.hu
@Date    : 2024
"""


# -------------------------------------
#  TraceIdFilter classes and functions
# -------------------------------------
class TraceIdFilter(logging.Filter):
    def filter(self, record):
        if has_app_context():
            if not hasattr(g, 'trace_id'):
                g.trace_id = str(uuid.uuid4())
            record.trace_id = g.trace_id
        else:
            record.trace_id = str(uuid.uuid4())
        return True
